//
//  WebserviceUtility.m
//  TestApp
//
//  Created by jwc on 2021/3/2.
//  Copyright © 2021 hyf. All rights reserved.
//

#import "WebserviceUtility.h"
#import "NSString+Base64.h"

#define WEBSERVICE_NAMESPACE @"http://service.wellhope.com/"
#define  timeOutInterval 15

@implementation WebserviceUtility

/**
 *  调webservice POST请求
 *  @param urlString webservice地址
 *  @param methodName webservice方法名
 *  @param params webservice参数:@[{@"content":@"%@"},@{@"extinfo1":@""},@{@"extinfo2":@""}];;
 *  @param success 调webservice成功之后的操作
 *  @param failure 调webservice失败之后的操作
 */
+(void)soapWithPostSessionManagerWithURL:(NSString *)urlString withMethodName:(NSString *)methodName withParams:(NSArray *)params success:(void (^)(id  responseObject))success
                      failure:(void (^)(NSError *error))failure
{
    //组装soap请求xml
    //根节点
    GDataXMLElement *root=[GDataXMLElement elementWithName:@"soap:Envelope"];
    //根节点的命名空间
    [root addNamespace:[GDataXMLNode namespaceWithName:@"xsi" stringValue:@"http://www.w3.org/2001/XMLSchema-instance"]];
    [root addNamespace:[GDataXMLNode namespaceWithName:@"xsd" stringValue:@"http://www.w3.org/2001/XMLSchema"]];
    [root addNamespace:[GDataXMLNode namespaceWithName:@"soap" stringValue:@"http://schemas.xmlsoap.org/soap/envelope/"]];
    //body
    GDataXMLElement *body=[GDataXMLElement elementWithName:@"soap:Body"];
    //消息体的命名空间
    GDataXMLNode *messageNS=[GDataXMLNode namespaceWithName:@"" stringValue:WEBSERVICE_NAMESPACE]; //方法上采用的是默认命名空间
    GDataXMLElement *message=[GDataXMLElement elementWithName:[NSString stringWithFormat:@"%@",methodName]];
    [message addNamespace:messageNS];
    
    for(int i = 0;i <params.count;i++)
    {
        NSDictionary*item= params[i];
        //参数列表
        NSArray *keys=[item allKeys];
        for (int i=0; i<[keys count]; i++) {
            id key=[keys objectAtIndex:i];
            id value=[item objectForKey:key];
            GDataXMLElement *methodParam=[GDataXMLElement elementWithName:key stringValue:value];
            [message addChild:methodParam];
        }
    }
    
    [body addChild:message];
    [root addChild:body];
    
    //组装ASIHttpRequest请求
    
    NSString*soapMessage =[NSString stringWithFormat:@"%@%@",@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n",[root XMLString]];
   // NSLog(@"请求的结构：%@",soapMessage);
    NSString *msgLength = [NSString stringWithFormat:@"%zd",[soapMessage length]];
    
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    [manager setSecurityPolicy:securityPolicy];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = timeOutInterval;
    [manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"%@%@",WEBSERVICE_NAMESPACE,methodName] forHTTPHeaderField:@"SOAPAction"];
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
        return soapMessage;
    }];
    
    [manager POST:urlString parameters:soapMessage headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        //NSLog(@"&&&&&&&&&--->%@",responseString);
        
        GDataXMLDocument *doc=[[GDataXMLDocument alloc] initWithData:responseObject options:0 error:nil];
        GDataXMLElement *root=[doc rootElement];
        NSString *aaa=[root XMLString];
        //NSLog(@"总的返回的结果：%@",aaa);
        NSDictionary *ns=[NSDictionary dictionaryWithObjectsAndKeys:@"http://schemas.xmlsoap.org/soap/envelope/",@"soapenv",WEBSERVICE_NAMESPACE,@"x", nil];
        NSString *path=[NSString stringWithFormat:@"//soapenv:Body/x:%@Response/x:%@Return",methodName,methodName];
        //采用XPath方式解析xml
        NSArray *resultArray=[root nodesForXPath:path namespaces:ns error:nil];
        if ([resultArray count] > 0) {
            GDataXMLElement *node=[resultArray objectAtIndex:0];
            NSString *XMLString = [node stringValue];
            //base64解码
            NSString *base64DecodedContent =[XMLString base64WithGBKDecodedString];
            success(base64DecodedContent);
            
            //NSLog(@"需要的返回结果解码前:--->%@",XMLString);
           // NSLog(@"需要的返回结果解码后:--->%@",base64DecodedContent);
            //         NSData *data=[[node stringValue] dataUsingEncoding:NSUTF8StringEncoding];
            //
            //            id result=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //            NSLog(@"返回的结果：%@",result);
        }else{
            success(@"");
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"错误：%@",error);
        failure(error);
    }];
}

/**
 *  调webservice GET请求
 *  @param urlString webservice地址
 *  @param params webservice参数:@[{@"content":@"%@"},@{@"extinfo1":@""},@{@"extinfo2":@""}];
 *  @param success 调webservice成功之后的操作
 *  @param failure 调webservice失败之后的操作
 */
+ (void)soapWithGetRESTWithURL:(NSString *)urlString withParams:(NSArray *)params success:(void (^)(id  responseObject))success failure:(void (^)(NSError *error))failure
{
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    [manager setSecurityPolicy:securityPolicy];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    manager.requestSerializer.timeoutInterval = timeOutInterval;
    //参数列表
    if (params.count>0) {
        urlString=[urlString stringByAppendingString:@"?"];
        
        for(int i = 0;i <params.count;i++)
        {
            NSDictionary*item  = params[i];
            NSArray *keys=[item allKeys];
            for (int i=0; i<[keys count]; i++) {
                id key=[keys objectAtIndex:i];
                id value=[item objectForKey:key];
                urlString =[urlString stringByAppendingFormat:@"%@=%@&",key,value];
            }
        }
        urlString = [urlString substringToIndex:urlString.length-1];
    }
    NSLog(@"%@",urlString);
    [manager GET:urlString parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSData *data=responseObject;
        NSString *result=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"成功：%@",result);
        success(result);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败：%@",error);
        failure(error);
    }];
}

@end
